import React, { useState, useEffect } from 'react';
import userService from '../services/userService';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext'; // 如果需要更新全局用户状态
import './FormStyles.css';

function UserProfilePage() {
    const [userData, setUserData] = useState({
        id: '',
        username: '',
        email: '',
        phoneNumber: '',
        fullName: '',
        address: '',
        dateOfBirth: ''
    });
    const [message, setMessage] = useState('');
    const [isLoading, setIsLoading] = useState(true);
    const [isSubmitting, setIsSubmitting] = useState(false);
    const navigate = useNavigate();
    const { currentUser, updateUser } = useAuth(); // 假设AuthContext有updateUser函数来更新全局用户状态

    useEffect(() => {
        const fetchUserProfile = async () => {
            try {
                const response = await userService.getCurrentUserProfile();
                setUserData(response.data);
                setIsLoading(false);
            } catch (error) { 
                console.error('Failed to fetch user profile:', error);
                if (error.response && error.response.status === 401) {
                    // 未登录或会话过期，重定向到登录页
                    navigate('/login');
                } else {
                    setMessage('获取用户信息失败，请稍后再试。');
                }
                setIsLoading(false);
            }
        };
        fetchUserProfile();
    }, [navigate]);

    const handleChange = (e) => {
        const { name, value } = e.target;
        setUserData(prevState => ({
            ...prevState,
            [name]: value
        }));
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        setMessage(''); // 清除之前的消息
        setIsSubmitting(true);
        
        try {
            const profileToUpdate = {
                email: userData.email,
                phoneNumber: userData.phoneNumber,
                fullName: userData.fullName,
                address: userData.address,
                dateOfBirth: userData.dateOfBirth
                // username通常不允许通过此表单直接更新
            };
            
            const response = await userService.updateCurrentUserProfile(profileToUpdate);
            setUserData(response.data); // 使用后端返回的数据更新状态
            
            // 如果需要，更新全局用户状态
            if (updateUser && currentUser) {
                updateUser({
                    ...currentUser,
                    email: response.data.email,
                    fullName: response.data.fullName
                });
            }
            
            setMessage('个人信息更新成功！');
        } catch (error) {
            console.error('Failed to update user profile:', error);
            if (error.response) {
                if (error.response.status === 401) {
                    // 未登录或会话过期
                    navigate('/login');
                } else if (error.response.data && error.response.data.message) {
                    setMessage(`更新失败: ${error.response.data.message}`);
                } else {
                    setMessage(`更新失败: ${error.response.statusText}`);
                }
            } else if (error.request) {
                // 请求已发送但没有收到响应
                setMessage('无法连接到服务器，请检查您的网络连接。');
            } else {
                // 其他错误
                setMessage('更新个人信息时出错，请稍后再试。');
            }
        } finally {
            setIsSubmitting(false);
        }
    };

    if (isLoading) {
        return <div className="form-container"><p>正在加载用户信息...</p></div>;
    }

    return (
        <div className="form-container">
            <h2>个人信息管理</h2>
            {message && (
                <div className={message.includes('成功') ? 'success-message' : 'error-message'}>
                    {message}
                </div>
            )}
            <form onSubmit={handleSubmit}>
                <div className="form-group">
                    <label htmlFor="username">用户名:</label>
                    <input
                        type="text"
                        id="username"
                        name="username"
                        value={userData.username || ''}
                        readOnly
                        className="readonly-input"
                    />
                    <small>用户名不可修改</small>
                </div>
                <div className="form-group">
                    <label htmlFor="fullName">姓名:</label>
                    <input
                        type="text"
                        id="fullName"
                        name="fullName"
                        value={userData.fullName || ''}
                        onChange={handleChange}
                        placeholder="请输入您的姓名"
                    />
                </div>
                <div className="form-group">
                    <label htmlFor="email">邮箱:</label>
                    <input
                        type="email"
                        id="email"
                        name="email"
                        value={userData.email || ''}
                        onChange={handleChange}
                        required
                        placeholder="请输入您的邮箱地址"
                    />
                </div>
                <div className="form-group">
                    <label htmlFor="phoneNumber">电话号码:</label>
                    <input
                        type="tel"
                        id="phoneNumber"
                        name="phoneNumber"
                        value={userData.phoneNumber || ''}
                        onChange={handleChange}
                        placeholder="请输入您的电话号码"
                    />
                </div>
                <div className="form-group">
                    <label htmlFor="address">地址:</label>
                    <input
                        type="text"
                        id="address"
                        name="address"
                        value={userData.address || ''}
                        onChange={handleChange}
                        placeholder="请输入您的地址"
                    />
                </div>
                <div className="form-group">
                    <label htmlFor="dateOfBirth">出生日期:</label>
                    <input
                        type="date"
                        id="dateOfBirth"
                        name="dateOfBirth"
                        value={userData.dateOfBirth || ''}
                        onChange={handleChange}
                    />
                    <small>格式: YYYY-MM-DD</small>
                </div>
                
                <button 
                    type="submit" 
                    className="submit-button" 
                    disabled={isSubmitting}
                >
                    {isSubmitting ? '正在更新...' : '更新信息'}
                </button>
            </form>
        </div>
    );
}

export default UserProfilePage; 